<?php

$MAX_IMAGE_FILE_SIZE = 4000000;
$OFFSET_PARAM_NAME = "_offset";

include '/../includes/utils.php';
session_start();
    if(isset($_SESSION['permisson']) && $_SESSION['permisson'] ==1){
        if(isset($_POST['uploadimage']))
        {
                upload_image();      
        }
    }
    else
        die();   
    
    
    function upload_image() {
        if (isset($_FILES['imageFile'])) { 
        $image_path="../images/ImageSlide";
         if(isset ($_POST['nameImage']))
            $upload_image_name = $_POST['nameImage'];
         else
             $upload_image_name="test";
         
         $sourceFile = $_FILES['imageFile']['name'];
         $typeFile = get_file_extension($sourceFile);
	$destination_file = $image_path . '/' . basename($upload_image_name).".".$typeFile;
	$pathDatabase = "images/ImageSlide/".basename($upload_image_name).".".$typeFile;        	
	       
	// Move file to destination images folder
        $fileTemplate = $_FILES['imageFile']['tmp_name'];       
	if(move_uploaded_file($fileTemplate, $destination_file)) {            
            if(isset ($_POST['showSlide']) && $_POST['showSlide'] == 'on')
                $bshow =1;
            else
                $bshow =0;
            
            $desc =$_POST['description'];
            //if(isset ($_POST['text_value']))
           // {
            //    $ar = (array)explode("\n",$_POST['text_value']);
            //    $desc=$ar[0];
           // }
            
                
    	// Add image record
         $connect = mysql_connect("localhost", "root","") or die("connect to mysql failed");
                    mysql_select_db("tripviet") or die("The database isn't exist");
        
                    $query = "INSERT INTO gallery (name, path, bshow,description)VALUES ('".$upload_image_name."','".$pathDatabase."','".$bshow."','".$desc."')"; 
                    mysql_query($query);
                    mysql_close($connect);
    	
	} else {
		echo "Image has larger size";
		// Move failed
		$dbs_error = "Unable to move uploaded image to destination folder: " . htmlspecialchars_default($destination_file);
		return FALSE;
		
	}
        }
 else {
    echo "input image";
}
}
    
 ?>

<html>
    <head>
        <title>ManagerImage</title>
        
        <script type="text/javascript">
            
            //Global variable
            bUpload = true;
            function loadImagepreview(){
                var sourceFile = document.getElementById("browserFile").value;
                if(sourceFile != ""){
                    buttonUpload = this.document.getElementsByName('uploadimage'); 
                    buttonUpload[0].disabled = false;
                    bUpload = true;
                }
                                               
            } 
            function getFormByName(sName){
                formArray = this.document.getElementsByTagName('form');
                for(i=0; i < formArray.length; i++){
                    if(formArray[i].name == sName)
                        return formArray[i];
                }
            }
            function hideBrowserFile(bHidden){
                browserArr = this.document.getElementsByName('imageFile');
                browserArr[0].hidden = bHidden;
                if(bHidden == false)
                   browserArr[0].value = ""; 
            }
            
            function changeLableFile(bDefault,nId){
                labelArr = this.document.getElementsByTagName('label');
                if(bDefault == true)
                    labelArr[0].textContent ='Image File:';
                else
                    labelArr[0].textContent = 'Id of Image:  '+nId;
            }
            
            
            function refreshForm()
            {
                formUpload = getFormByName('upload');
                //get
                changeLableFile(true,'');
                hideBrowserFile(false);
                
            }
             function onEditImage(nPos)
                {
                    GalleryObj = this.document.getElementById('gridshow');
                    var Images = GalleryObj.getElementsByTagName('IMG');
                    
                    hideBrowserFile(true);
                    
                   
                     alt_value = Images[nPos].alt;
                     
                     arr_result = alt_value.split(";");  
                     changeLableFile(false,arr_result[0]);                      
                     checkBox_show = this.document.getElementsByName('showSlide');
                     if(arr_result[2] == "1"){                                                     
                            checkBox_show[0].checked =true; 
                         }
                         else
                             checkBox_show[0].checked =false;                    
                    
                    nameImg = this.document.getElementsByName('nameImage');
                    nameImg[0].value =arr_result[1];
                    
                    descArea = this.document.getElementsByName('description');
                    descArea[0].value = arr_result[3];
                    buttonUpload = this.document.getElementsByName('uploadimage');
                    buttonUpload[0].disabled = false;
                    buttonUpload[0].value = "Update";                   
                    
                    buttonCancel = this.document.getElementsByName('reset');
                    buttonCancel[0].hidden = false;
                    bUpload = false;
                    
                    
                }
                function uploadImage(){
                   if(bUpload)
                       {
                           var xmlhttp;
                    if (window.XMLHttpRequest)
                      {// code for IE7+, Firefox, Chrome, Opera, Safari
                      xmlhttp=new XMLHttpRequest();
                      }
                    else
                      {// code for IE6, IE5
                      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                      }
                    xmlhttp.onreadystatechange=function()
                      {
                      if (xmlhttp.readyState==4 && xmlhttp.status==200)
                            {
                                if(xmlhttp.responseText == "Success")
                                    alert"Upload successful";
                            }
                      }
                            xmlhttp.open("GET","getImagedata.php",true);
                            xmlhttp.send();
                       }
                    
                else
                    alert('Update');
                }
                function gotoNewPage(nPage)
                {
                    var xmlhttp;
                    if (window.XMLHttpRequest)
                      {// code for IE7+, Firefox, Chrome, Opera, Safari
                      xmlhttp=new XMLHttpRequest();
                      }
                    else
                      {// code for IE6, IE5
                      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                      }
                    xmlhttp.onreadystatechange=function()
                      {
                      if (xmlhttp.readyState==4 && xmlhttp.status==200)
                            {							
                                            alert(xmlhttp.responseText);
                            }
                      }
                    xmlhttp.open("GET","getImagedata.php",true);
                    xmlhttp.send();
                }
        </script>
       <link rel="stylesheet" type="text/css" href="css/adminStyle.css" />
       <style type="text/css">
           ul.nav {overflow: hidden; padding: 0px;}
            ul.nav li { display: inline; float: left;margin: 0px 5px;background: #8AB1FE;}
            /*ul.nav li a {color: white;text-decoration: none;display: block; padding: 3px 8px;}*/
            ul.nav li:hover {background: #3A7ABE;}
            ul.nav li.current {font-weight: bold; padding: 3px 8px; }
            
            ul.nav li{cursor: pointer;}
            #gridshow img{
                cursor: pointer;
            }
       </style>
    </head>
    <body>
        
        <form name="Upload" method="post" action="" enctype="multipart/form-data">
        <fieldset style="width: 960px; margin: 0px auto;">
        <legend>Upload Image</legend>
        <div id="controlLeft" style="margin: 0px auto;">
        <input type="hidden" name="MAX_FILE_SIZE" />
        <label for="imageFile">Image File:</label>
        <input id="browserFile" name="imageFile"  type="file" onChange="loadImagepreview();" size="40" style="margin-left: 29px;margin-top: 5px;"/><br />
        <a href="#" id="myframe"></a>

        <label for="imageName">Image name:</label>
        <input type="text" name="nameImage" style="margin-left: 20px;margin-top: 5px;"/><br />
        <label for="slideshow">Show slide:</label>
        <input type="checkbox" name="showSlide" style="margin-left: 25px;margin-top: 5px;"/><br />
        <label for="description">Description:</label><br />
        <textarea cols="40" rows="4" name="description" style="margin-left: 100px;margin-top: 5px;"></textarea>
        <br />
        <input type="button" name="uploadimage" value="Upload" disabled="disabled" onclick="uploadImage();" style="margin-left:200px;margin-top: 5px;"/>
        <input type="button" name="reset" value="Cancel" hidden="true" onclick="refreshForm();"/>
        </div>
  
        </fieldset>  
        </form>


        <form>
            <fieldset style="width: 960px; margin: 0px auto;">
               <legend >Image on server</legend>
                <div id="gridshow" style="margin: 0px auto; float:left;">
                        <?php
                            //Connect to server
                            $connection = mysqli_connect('localhost','root','','tripviet') or die('Could not connect to DB');
                            //get the number the images in the sever
                            $query = "SELECT COUNT(id) FROM gallery";
                            $display = 10;
                            $res = mysqli_query($connection,$query) or die('Could not select users '.mysqli_error($connection));
                            $rows = mysqli_fetch_array($res, MYSQLI_NUM);
                            $record = $rows[0];
                            if($record > $display) {
                                $page = ceil($record/$display);
                            } else {
                                $page = 1;
                            }
                            $start =0;
                            $nID =0;
                            $sql = "SELECT id,
                                    name,
                                    path,
                                    bshow,
                                    description
                                    FROM gallery                    
                                    LIMIT $start, $display";
                            $result = mysqli_query($connection,$sql) or die('Could not select email '.mysqli_error($connect));
                            while($set = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                                $idImg = $set['id'];
                                $name = $set['name'];
                                $path = $set['path'];
                                $bShow = $set['bshow'];
                                $desc = $set['description'];
                                echo '<img src="../'.$path.'" height="130" width="130" onclick="'.'onEditImage('.($nID).');" alt="'.$idImg.';'.$name.';'.$bShow.';'.$desc.'"/>';
                                $nID++;
                            }
                            
                            
                        ?>
                    <ul class="nav">
                        <?php
                        $next = $start + $display;
                            $prev = $start - $display;
                            $current = ($start/$display)+1;
                               for($i=1;$i<=$page;$i++) {
                                if($current != $i) {
                                echo '<li class="current" onclick="'.'gotoNewPage('.($i).');" >'.$i.'</li>';
                            } else 
                                echo '<li class="current" onclick="'.'gotoNewPage('.($i).');" >'.$i.'</li>';
                            
                            } //End: FOR
                        ?>
                    </ul>
                </div>

            </fieldset>
        </form>
    </body>   
 </html>